//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

use git2::{Error, Repository};
use serde::Serialize;
use std::path::PathBuf;

#[derive(Serialize, Clone, Debug)]
struct RemoteInfo {
    name: String,
    url: String,
}

pub fn exec(git_path: PathBuf) -> Result<(), Error> {
    let repo = Repository::open(git_path);
    if repo.is_err() {
        return Err(repo.err().unwrap());
    }
    let repo = repo.unwrap();

    let remotes = repo.remotes();
    if remotes.is_err() {
        return Err(remotes.err().unwrap());
    }
    let mut ret_list = Vec::new();
    let remotes = remotes.unwrap();
    for remote in &remotes {
        if remote.is_none() {
            continue;
        }
        let remote = remote.unwrap();
        let info = repo.find_remote(remote);
        if info.is_err() {
            continue;
        }
        let info = info.unwrap();
        let name = info.name();
        if name.is_none() {
            continue;
        }
        let url = info.url();
        if url.is_none() {
            continue;
        }
        ret_list.push(RemoteInfo {
            name: String::from(name.unwrap()),
            url: String::from(url.unwrap()),
        });
    }
    println!("{}", serde_json::to_string(&ret_list).unwrap());

    return Ok(());
}
